<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\model\MemberCommissionRate;
use app\api\model\Mp;
use app\api\model\MemberSite;

use app\api\model\User;
use app\api\model\UserBalanceRecord;
use app\api\model\UserDrawApply;
use app\api\model\UserReply;
use app\api\model\UserTbOauth;
use app\api\model\UserTbOrder;
use app\BaseController;
use think\facade\Log;

class Wechat extends BaseController
{


    public function index()
    {
        $t1=microtime(true);
        $id = $this->request->param('id');
        $Mpdata = Mp::find($id);
        $options = array(
            'token' => $Mpdata->valid_token, //填写你设定的key
            'encodingaeskey' => $Mpdata->encodingaeskey, //填写加密用的EncodingAESKey
            'appid' => $Mpdata->appid, //填写高级调用功能的app id
            'appsecret' => $Mpdata->appsecret //填写高级调用功能的密钥
        );
        $weObj = new \wechatSdk\Wechat($options);
        if ($weObj->valid()) {
            Mp::update(['state' => 1], ['id' => $id]);
        }
        $type = $weObj->getRev()->getRevType();
        switch ($type) {
            case 'text':
                $postarr = $weObj->getRev()->getRevData();
                $resdata = $this->tomsg($id, $postarr);


                $weObj->text($resdata)->reply();
                exit;
                break;
            case  'image' :
                // ....
                break;
            case 'event':
                // ...
                break;
            default:
                $weObj->text("help info")->reply();
        }


    }


    /**
     * User: tomsg
     * Notes:消息处理主函数
     * @param array $postarr
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function tomsg(string $id, array $postarr)
    {
        //log::write($postarr,'diy');die;

        $ToUserName = $postarr['FromUserName'];
        $FromUserName = $postarr['ToUserName'];
        $Content = $postarr['Content'];
        //判断是不是会员FromUserName
        $Userdata = User::where('openid', $ToUserName)->find();


        if (!$Userdata) {
            //把用户资料写入数据库建档
            $data = ['openid' => (string)$ToUserName];
            User::create($data);
        }
        if ($Content == '签到') {
            $data = '签到成功';
            return $data;
        }
        if ($Content == '提现') {
            //判断提现金额必须大于几元的整数
            //SetSys

            $Systemdata = MemberSite::where('robot_id', $FromUserName)->field('draw_limit_money,draw_method,draw_auto_money')->find();
            log::write($Systemdata,'diy');

            if ($Userdata->effec_money <= $Systemdata->draw_limit_money) {
                //发送金钱不足    提现金额必须大于元的整数
                $data = "提现金额必须大于" . $Systemdata->draw_limit_money . "元的整数";
                return $data;
            } else {
                //判断今天是否已提现
                $UserDrawApply = new UserDrawApply;
                $res_exist = $UserDrawApply->where('openid', $Userdata->openid)->where('is_check', '0')->find();
                if ($res_exist) {
                    $data = '有提现任务在审核';
                    return $data;
                }
                //判断用户提现模式 DRAW_METHOD 3自动 1手动
                if ($Systemdata[0]->draw_method = '3' and $Userdata->effec_money <= $Systemdata[0]->draw_auto_money) {
                    $data = [
                        'openid' => $Userdata->openid,
                        'money' => $Userdata->effec_money,
                        'apply_time' => time(),
                        'is_check' => '1',//已审核
                        'check_result' => '1',//审核通过
                        'check_time' => time()
                    ];
                    //开启事务
                    $UserDrawApply->startTrans();
                    //创建提现订单
                    $res_add = $UserDrawApply->create($data);
                    //修改用户余额
                    $res_balance = User::where('openid', $Userdata->openid)->inc('take_money', (float)$Userdata->effec_money)->dec('effec_money', (float)$Userdata->effec_money)->update();
                    //记录用户余额变动记录
                    $UserBalanceRecord = new UserBalanceRecord();
                    $all_money = $Userdata->effec_money - $Userdata->effec_money;
                    //保留2位小数，四舍五入
                    $all_money = round($all_money, 2);
                    $res_record = $UserBalanceRecord->create([
                        'remark' => '成功提现减去' . $Userdata->effec_money,
                        'openid' => $Userdata->openid,
                        'all_money' => $all_money,
                        'money' => $Userdata->effec_money
                    ]);
                    if ($res_add and $res_balance !== false and $res_record) {
                        //提交事务
                        $UserDrawApply->commit();
                        $oneinfodata = '提现成功';

                        //  //单笔转账到支付宝账号
                        //  //获取支付宝请求参数
                        //  Vendor('pay.alipayApp','','.class.php');
                        //  $alipayApp=new \alipayApp();
                        //  $out_biz_no=time().'_'.$res_add;
                        //  $payee_account=trim(I('post.account'));
                        //  $amount=$money;
                        //  $payer_show_name=APP_NAME;//付款方姓名
                        //  $payee_real_name=trim(I('post.truename'));//收款方真实姓名
                        //  $res_ali=$alipayApp->fundTransToaccountTransfer($out_biz_no, $payee_account, $amount,$payer_show_name,$payee_real_name);
                        //  if($res_ali['code']===0) {

                        //  }else {
                        //      //转账失败
                        //      /* $res=array(
                        //       'code'=>$this->ERROR_CODE_COMMON['DB_ERROR'],
                        //       'msg'=>$res_ali['msg']
                        //       ); */
                        //      $error_msg='支付宝转账失败：'.$res_ali['msg'].',账号：'.$payee_account.'，姓名：'.$payee_real_name;
                        //      writeLog($error_msg);
                        //  }
                        return $oneinfodata;
                    } else {
                        //回滚
                        $UserDrawApply->rollback();
                        //数据库错误
                        //$res=array('code'=>$this->ERROR_CODE_COMMON['DB_ERROR'],'msg'=>$this->ERROR_CODE_COMMON_ZH[$this->ERROR_CODE_COMMON['DB_ERROR']]);
                    }
                } else {
                    //超过限制的提现需要审核
                    $data = [
                        'openid' => $Userdata->openid,
                        'money' => $Userdata->effec_money,
                        'apply_time' => time(),
                        'is_check' => '0',//未审核，等待审核
                    ];
                    $res = $UserDrawApply->create($data);
                    if ($res) {
                        $oneinfodata = "提现申请成功，请等待管理员审核！";

                    } else {
                        //数据库错误
                        // $res=array('code'=>$this->ERROR_CODE_COMMON['DB_ERROR'],'msg'=>$this->ERROR_CODE_COMMON_ZH[$this->ERROR_CODE_COMMON['DB_ERROR']]);
                    }
                }
                return $oneinfodata;
            }

        }


        //匹配订单号
        if (preg_match('/[0-9]{19}/', (string)$Content, $matcharr)) {
            $Ordermodel = new UserTbOrder();
            $res = $Ordermodel->where('trade_parent_id', $matcharr[0])->find();
            //查询数据库里是否有该订单数据
            if ($res) {
                //先判断该订单是否已有绑定用户了
                if (!$res->openid) {
                    $data = ['id' => $res->id, 'openid' => (string)$ToUserName];
                    if ($Ordermodel->Update($data)) {
                        //把订单佣金计算到用户数据库中
                        //订单数据  下单价 total_price*佣金比total_commission_rate*用户佣金比获取数据库用户数据

                        $TempData = $res->total_price * $res->total_commission_rate / 100 * 70 / 100;
                        //把下单佣金写入用户数据库中
                        User::where('openid', $ToUserName)->inc('effec_money', $TempData)->inc('order_num')->update();


                        // Log::write($TempData,'notice');die;

                        $info = config('msg.text');
                        $data = sprintf($info, $ToUserName, $FromUserName, '绑定成功');

                        return $data;
                    }
                } else {
                    $info = config('msg.text');
                    //之后获取数据库里的文案数据替换info
                    $data = sprintf($info, $ToUserName, $FromUserName, '已别人其他绑定');
                    return $data;
                }


            } else {
                $info = config('msg.text');
                //之后获取数据库里的文案数据替换info
                $data = sprintf($info, $ToUserName, $FromUserName, '系统没有订单');
                return $data;
            }


            $info = config('msg.text');
            $data = sprintf($info, $ToUserName, $FromUserName, $Ordermodel);
            // Log::write($Ordermodel,'notice');
            return $data;

        }


        //匹配淘口令
        if (preg_match('/[a-zA-Z0-9]{11,13}/', (string)$Content, $matcharr)) {
            //log::write($matcharr[0],'notice');
            $tkl = $matcharr[0];
            $Mpdata = Mp::where('mp_user', (string)$FromUserName)->find();
            $UserTbOauthdata = UserTbOauth::where('uid', $Mpdata['uid'])->find();
            //            MemberCommissionRate::where('mp_user',$Mpdata['uid'])->find();
            $url = 'https://api.zhetaoke.com:10001/api/open_gaoyongzhuanlian_tkl.ashx?appkey=47117b1f637b4986bae65cab9b4df54f&sid=' . $UserTbOauthdata['sid'] . '&pid=' . $Mpdata['pid'] . '&tkl=' . $tkl . '&signurl=5';
            $res = https_request($url);

            $res = json_decode($res, true);
if($res['status']==301){
    return '口令失败';
}
            $data = $res['content'][0];
            //淘口令
            $tpwd = $data['tkl'];
            //佣金比例
            $maxCommissionRate = $data['tkrate3'];
            //券后价
            $actualPrice = $data['quanhou_jiage'];
            //优惠券面额
            $couponInfo = $data['coupon_info_money'];

            //            if (preg_match_all('/\d+/', $couponInfo, $matcharr)) {
            ////                //log::write($matcharr[0][1],'notice');
            /// //                $couponInfo = $matcharr[0][1];
            /// //
            /// //            }
            //判断淘口令有商品就进线转口令和获取佣金比，判断是否有优惠券返回文案，无商品返回，，错误文案
            $robot_reply = UserReply::where('robot_id', $FromUserName)->find();
            if ($couponInfo) {
                //有优惠券文案 tb_yes_coupon
                $res_robot_reply = $robot_reply['tb_text_yes_coupon'];
                //计算商品联盟佣金
                $counts = $actualPrice * $maxCommissionRate / 100;
                if ($Userdata['commission_str']) {
                    //用户有专属佣金比
                    $array = explode('|', $Userdata->commission_str);
                    //循环对比用户阶段佣金比
                    foreach ($array as $value) {
                        $arr = explode(':', $value);
                        if ($counts > $arr[0]) {
                            $Userrebate = round($counts * $arr[1] / 100, 2);
                        }
                    }
                } else {
                    //用户无专属佣金比，获取机器人默认设置
                    $robotCommissionRate = MemberCommissionRate::where('robot_id', $FromUserName)->where('name', '默认返利')->find();
                    $array = explode('|', $robotCommissionRate->commission_str);
                    //循环对比用户阶段佣金比
                    foreach ($array as $value) {
                        $arr = explode(':', $value);
                        if ($counts > $arr[0]) {
                            $Userrebate = round($counts * $arr[1] / 100, 2);
                        }
                    }
                }
                //可用变量： [名称]x [淘口令] [积分名称] [补贴金额] [抢购链接]x [券后价格] [商品价格] [商品标题] [优惠券面额] [省钱] [到手价]
                /**
                 * $res_robot_reply=str_replace("[名称]",(string)$tklres->data->originInfo->title,$res_robot_reply);
                 */

                $res_robot_reply = str_replace("[淘口令]", (string)$tpwd, $res_robot_reply);
                $res_robot_reply = str_replace("[商品价格]", (string)$data['size'], $res_robot_reply);
                $res_robot_reply = str_replace("[补贴金额]", (string)$Userrebate, $res_robot_reply);
                $res_robot_reply = str_replace("[券后价格]", (string)$actualPrice, $res_robot_reply);
                $res_robot_reply = str_replace("[商品标题]", (string)$data['tao_title'], $res_robot_reply);
                $res_robot_reply = str_replace("[优惠券面额]", 'ouponInfo', $res_robot_reply);

                // $res_robot_reply=str_replace("[省钱]",(string)$res->data->originalPrice,$res_robot_reply);
                // $res_robot_reply=str_replace("[商品价格]",(string)$res->data->originalPrice,$res_robot_reply);



            } else {
                //无优惠券文案 tb_no_coupon
                $res_robot_reply = $robot_reply['tb_text_no_coupon'];
                //计算商品联盟佣金

                $counts = $actualPrice * $maxCommissionRate / 100;
                if ($Userdata->commission_str) {
                    //用户有专属佣金比
                    $array = explode('|', $Userdata->commission_str);
                    //循环对比用户阶段佣金比
                    foreach ($array as $value) {
                        $arr = explode(':', $value);
                        if ($counts > $arr[0]) {
                            $Userrebate = round($counts * $arr[1] / 100, 2);
                        }
                    }
                } else {
                    //用户无专属佣金比，获取机器人默认设置
                    $robotCommissionRate = MemberCommissionRate::where('robot_id', $FromUserName)->where('name', '默认返利')->find();
                    $array = explode('|', $robotCommissionRate->commission_str);
                    //循环对比用户阶段佣金比
                    foreach ($array as $value) {
                        $arr = explode(':', $value);
                        if ($counts > $arr[0]) {
                            $Userrebate = round($counts * $arr[1] / 100, 2);
                        }
                    }
                }
                //可用变量： 可用变量： [名称] [淘口令] [积分名称] [补贴金额] [抢购链接] [商品价格] [商品标题] [省钱] [到手价]
                $res_robot_reply = str_replace("[淘口令]", (string)$tpwd, $res_robot_reply);
                $res_robot_reply = str_replace("[商品价格]", (string)$data['size'], $res_robot_reply);
                $res_robot_reply = str_replace("[补贴金额]", (string)$Userrebate, $res_robot_reply);
                $res_robot_reply = str_replace("[商品标题]", (string)$data['tao_title'], $res_robot_reply);


            }
            log::write($res_robot_reply,'notice');
            return $res_robot_reply;
        }


        return $Content;

    }


}
